<template>
  <div class="coach-certificate-list">
    <el-card class="certificate-card">
      <template #header>
        <div class="card-header">
          <span>教练证书管理</span>
          <div class="header-actions">
            <el-select
              v-model="searchForm.coachId"
              placeholder="选择教练"
              clearable
              filterable
              style="width: 200px; margin-right: 10px"
              @change="handleSearch"
            >
              <el-option
                v-for="coach in coachOptions"
                :key="coach.id"
                :label="coach.name"
                :value="coach.id"
              />
            </el-select>
            <el-select
              v-model="searchForm.status"
              placeholder="审核状态"
              clearable
              style="width: 150px; margin-right: 10px"
              @change="handleSearch"
            >
              <el-option label="全部状态" value="" />
              <el-option label="待审核" value="PENDING" />
              <el-option label="已通过" value="APPROVED" />
              <el-option label="已拒绝" value="REJECTED" />
            </el-select>
            <el-button type="primary" @click="handleUpload">上传证书</el-button>
            <el-button @click="handleRefresh">刷新</el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="certificateList"
        v-loading="loading"
        style="width: 100%"
        row-key="id"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="证书预览" width="150">
          <template #default="scope">
            <div class="certificate-preview">
              <el-image
                :src="scope.row.fileUrl"
                :preview-src-list="[scope.row.fileUrl]"
                fit="cover"
                class="preview-image"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="coach.name" label="教练" width="120" />
        <el-table-column prop="certificateName" label="证书名称" show-overflow-tooltip />
        <el-table-column prop="certificateNo" label="证书编号" width="150" />
        <el-table-column prop="issueDate" label="颁发日期" width="120" />
        <el-table-column prop="expireDate" label="有效期至" width="120" />
        <el-table-column prop="status" label="审核状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ formatStatus(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="上传时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button
              size="small"
              type="success"
              @click="handleVerify(scope.row, 'APPROVED')"
              v-if="scope.row.status === 'PENDING'"
            >
              通过
            </el-button>
            <el-button
              size="small"
              type="warning"
              @click="handleVerify(scope.row, 'REJECTED')"
              v-if="scope.row.status === 'PENDING'"
            >
              拒绝
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="table-actions">
        <el-button
          type="danger"
          :disabled="selectedCertificates.length === 0"
          @click="handleBatchDelete"
        >
          批量删除 ({{ selectedCertificates.length }})
        </el-button>
      </div>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 上传证书对话框 -->
    <el-dialog
      v-model="uploadDialogVisible"
      title="上传教练证书"
      width="600px"
    >
      <el-form
        ref="uploadFormRef"
        :model="uploadForm"
        :rules="uploadRules"
        label-width="120px"
      >
        <el-form-item label="证书图片" prop="file">
          <el-upload
            class="certificate-uploader"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="handleCertificateChange"
          >
            <img
              v-if="uploadForm.imageUrl"
              :src="uploadForm.imageUrl"
              class="certificate"
            />
            <el-icon v-else class="certificate-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="证书名称" prop="certificateName">
          <el-input
            v-model="uploadForm.certificateName"
            placeholder="请输入证书名称"
            :maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="证书编号" prop="certificateNo">
          <el-input
            v-model="uploadForm.certificateNo"
            placeholder="请输入证书编号"
            :maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="颁发日期" prop="issueDate">
          <el-date-picker
            v-model="uploadForm.issueDate"
            type="date"
            placeholder="选择颁发日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="有效期至" prop="expireDate">
          <el-date-picker
            v-model="uploadForm.expireDate"
            type="date"
            placeholder="选择有效期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="颁发机构" prop="issuingAuthority">
          <el-input
            v-model="uploadForm.issuingAuthority"
            placeholder="请输入颁发机构"
            :maxlength="100"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="uploadDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitUpload"
            :loading="uploadLoading"
          >
            上传
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 证书详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="证书详情"
      width="800px"
    >
      <div class="certificate-detail">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-image
              :src="currentCertificate.fileUrl"
              :preview-src-list="[currentCertificate.fileUrl]"
              fit="contain"
              style="width: 100%; height: 400px"
            />
          </el-col>
          <el-col :span="12">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="证书ID">{{ currentCertificate.id }}</el-descriptions-item>
              <el-descriptions-item label="教练">教练ID: {{ currentCertificate.coachId }}</el-descriptions-item>
              <el-descriptions-item label="证书名称">{{ currentCertificate.certificateName }}</el-descriptions-item>
              <el-descriptions-item label="证书编号">{{ currentCertificate.certificateNo || '-' }}</el-descriptions-item>
              <el-descriptions-item label="颁发日期">{{ currentCertificate.issueDate || '-' }}</el-descriptions-item>
              <el-descriptions-item label="有效期至">{{ currentCertificate.expireDate || '-' }}</el-descriptions-item>
              <el-descriptions-item label="颁发机构">{{ currentCertificate.issuingAuthority || '-' }}</el-descriptions-item>
              <el-descriptions-item label="审核状态">
                <el-tag :type="getStatusTagType(currentCertificate.status)">
                  {{ formatStatus(currentCertificate.status) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="拒绝原因" v-if="currentCertificate.rejectReason">
                {{ currentCertificate.rejectReason }}
              </el-descriptions-item>
              <el-descriptions-item label="审核时间" v-if="currentCertificate.verifiedAt">
                {{ currentCertificate.verifiedAt }}
              </el-descriptions-item>
              <el-descriptions-item label="上传时间">{{ currentCertificate.createdAt }}</el-descriptions-item>
            </el-descriptions>
          </el-col>
        </el-row>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleDownload(currentCertificate)">下载</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 审核证书对话框 -->
    <el-dialog
      v-model="verifyDialogVisible"
      :title="`审核证书 - ${currentCertificate.certificateName}`"
      width="500px"
    >
      <el-form
        ref="verifyFormRef"
        :model="verifyForm"
        :rules="verifyRules"
        label-width="80px"
      >
        <el-form-item label="审核结果" prop="status">
          <el-radio-group v-model="verifyForm.status">
            <el-radio label="APPROVED">通过</el-radio>
            <el-radio label="REJECTED">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          label="拒绝原因"
          prop="rejectReason"
          v-if="verifyForm.status === 'REJECTED'"
        >
          <el-input
            v-model="verifyForm.rejectReason"
            type="textarea"
            :rows="3"
            placeholder="请输入拒绝原因"
            :maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="verifyDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitVerify"
            :loading="verifyLoading"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { UploadFile } from 'element-plus'
import type {
  CoachCertificate,
  UploadCoachCertificateRequest,
  VerifyCertificateRequest
} from '@/types/api/file'
import { coachCertificateApi } from '@/api/modules/file'
import { preventDuplicateSubmit, formUtils } from '@/utils'

// 表格相关
const loading = ref(false)
const certificateList = ref<CoachCertificate[]>([])
const currentCertificate = ref<CoachCertificate>({
  id: 0,
  coachId: 0,
  fileId: 0,
  fileUrl: '',
  certificateName: '',
  certificateNo: '',
  issueDate: '',
  expireDate: '',
  issuingAuthority: '',
  status: 'PENDING',
  rejectReason: '',
  verifiedAt: '',
  verifiedBy: 0,
  createdAt: '',
  updatedAt: ''
})

// 搜索表单
const searchForm = reactive({
  coachId: undefined as number | undefined,
  status: ''
})

// 分页相关
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 对话框相关
const uploadDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const verifyDialogVisible = ref(false)
const uploadLoading = ref(false)
const verifyLoading = ref(false)
const uploadFormRef = ref()
const verifyFormRef = ref()

// 上传表单数据
const uploadForm = reactive({
  file: null as File | null,
  imageUrl: '',
  certificateName: '',
  certificateNo: '',
  issueDate: '',
  expireDate: '',
  issuingAuthority: ''
})

// 审核表单数据
const verifyForm = reactive({
  status: 'APPROVED' as 'APPROVED' | 'REJECTED',
  rejectReason: ''
})

// 选中的证书
const selectedCertificates = ref<CoachCertificate[]>([])

// 模拟教练选项
const coachOptions = ref([
  { id: 1, name: '张教练' },
  { id: 2, name: '李教练' },
  { id: 3, name: '王教练' }
])

// 表单验证规则
const uploadRules = {
  file: [
    { required: true, message: '请上传证书图片', trigger: 'change' }
  ],
  certificateName: [
    { required: true, message: '请输入证书名称', trigger: 'blur' }
  ]
}

const verifyRules = {
  status: [
    { required: true, message: '请选择审核结果', trigger: 'change' }
  ],
  rejectReason: [
    { required: true, message: '请输入拒绝原因', trigger: 'blur' }
  ]
}

// 获取教练证书列表
const getCoachCertificateList = async () => {
  try {
    loading.value = true
    const params: any = {
      page: pagination.page,
      pageSize: pagination.pageSize
    }

    if (searchForm.coachId) {
      params.coachId = searchForm.coachId
    }

    if (searchForm.status) {
      params.status = searchForm.status
    }

    const response = await coachCertificateApi.getCoachCertificateList(params)
    certificateList.value = response.data.data.list
    pagination.total = response.data.data.total
  } catch (error) {
    ElMessage.error('获取教练证书列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  getCoachCertificateList()
}

// 刷新列表
const handleRefresh = () => {
  getCoachCertificateList()
}

// 处理证书文件变化
const handleCertificateChange = (uploadFile: UploadFile) => {
  if (uploadFile.raw) {
    uploadForm.file = uploadFile.raw
    uploadForm.imageUrl = URL.createObjectURL(uploadFile.raw)
  }
}

// 上传证书
const handleUpload = () => {
  // 重置表单
  uploadForm.file = null
  uploadForm.imageUrl = ''
  uploadForm.certificateName = ''
  uploadForm.certificateNo = ''
  uploadForm.issueDate = ''
  uploadForm.expireDate = ''
  uploadForm.issuingAuthority = ''
  uploadDialogVisible.value = true
}

// 提交上传
const submitUpload = async () => {
  if (!uploadFormRef.value) return

  try {
    await uploadFormRef.value.validate()

    if (!uploadForm.file) {
      ElMessage.warning('请上传证书图片')
      return
    }

    // 使用防重复提交保护
    await preventDuplicateSubmit('upload_coach_certificate', async () => {
      uploadLoading.value = true

      try {
        const uploadData: UploadCoachCertificateRequest = {
          file: uploadForm.file!,
          certificateName: uploadForm.certificateName,
          certificateNo: uploadForm.certificateNo,
          issueDate: uploadForm.issueDate,
          expireDate: uploadForm.expireDate,
          issuingAuthority: uploadForm.issuingAuthority
        }

        const res = await coachCertificateApi.uploadCoachCertificate(uploadData)
        ElMessage.success('证书上传成功，等待审核')
        uploadDialogVisible.value = false
        getCoachCertificateList()
      } catch (error: any) {
        ElMessage.error('证书上传失败')
        throw error // 重新抛出错误以确保防重复提交正确处理
      } finally {
        uploadLoading.value = false
      }
    })
  } catch (error: any) {
    // 防重复提交保护捕获的错误
    if (error.message === '请勿重复提交') {
      ElMessage.warning('请勿重复提交')
    }
  }
}

// 查看证书详情
const handleView = (row: CoachCertificate) => {
  currentCertificate.value = row
  detailDialogVisible.value = true
}

// 审核证书
const handleVerify = (row: CoachCertificate, status: 'APPROVED' | 'REJECTED') => {
  currentCertificate.value = row
  verifyForm.status = status
  verifyForm.rejectReason = ''
  verifyDialogVisible.value = true
}

// 提交审核
const submitVerify = async () => {
  if (!verifyFormRef.value) return

  try {
    await verifyFormRef.value.validate()

    // 使用防重复提交保护
    await preventDuplicateSubmit(`verify_certificate_${currentCertificate.value.id}`, async () => {
      verifyLoading.value = true

      try {
        const verifyData: VerifyCertificateRequest = {
          status: verifyForm.status,
          rejectReason: verifyForm.rejectReason
        }

        await coachCertificateApi.verifyCoachCertificate(currentCertificate.value.id, verifyData)
        ElMessage.success('审核操作成功')
        verifyDialogVisible.value = false
        getCoachCertificateList()
      } catch (error: any) {
        ElMessage.error('审核操作失败')
        throw error // 重新抛出错误以确保防重复提交正确处理
      } finally {
        verifyLoading.value = false
      }
    })
  } catch (error: any) {
    // 防重复提交保护捕获的错误
    if (error.message === '请勿重复提交') {
      ElMessage.warning('请勿重复提交')
    }
  }
}

// 删除证书
const handleDelete = async (row: CoachCertificate) => {
  formUtils.handleDeleteConfirm(`证书 "${row.certificateName}"`, async () => {
    await coachCertificateApi.deleteCoachCertificate(row.id)
    getCoachCertificateList()
  }, {
    successMessage: '删除成功',
    errorMessage: '删除失败'
  })
}

// 批量删除证书
const handleBatchDelete = async () => {
  if (selectedCertificates.value.length === 0) {
    ElMessage.warning('请至少选择一个证书')
    return
  }

  formUtils.handleBatchDeleteConfirm(
    selectedCertificates.value.length,
    '证书',
    async () => {
      // 批量删除
      for (const certificate of selectedCertificates.value) {
        await coachCertificateApi.deleteCoachCertificate(certificate.id)
      }
      selectedCertificates.value = []
      getCoachCertificateList()
    },
    {
      successMessage: '批量删除成功',
      errorMessage: '批量删除失败'
    }
  )
}

// 下载证书
const handleDownload = (row: CoachCertificate) => {
  // 创建一个隐藏的a标签来下载证书
  const link = document.createElement('a')
  link.href = row.fileUrl
  link.download = `${row.certificateName}.jpg`
  link.style.display = 'none'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 处理选中变化
const handleSelectionChange = (selection: CoachCertificate[]) => {
  selectedCertificates.value = selection
}

// 分页相关方法
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  getCoachCertificateList()
}

const handleCurrentChange = (val: number) => {
  pagination.page = val
  getCoachCertificateList()
}

// 格式化状态
const formatStatus = (status: string) => {
  const statusMap: Record<string, string> = {
    'PENDING': '待审核',
    'APPROVED': '已通过',
    'REJECTED': '已拒绝'
  }
  return statusMap[status] || status
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const statusMap: Record<string, string> = {
    'PENDING': 'warning',
    'APPROVED': 'success',
    'REJECTED': 'danger'
  }
  return statusMap[status] || 'info'
}

// 生命周期
onMounted(() => {
  getCoachCertificateList()
})
</script>

<style scoped>
.coach-certificate-list {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-actions {
  margin: 20px 0;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.certificate-preview {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 120px;
  height: 120px;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.certificate-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.certificate-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.certificate-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.certificate {
  width: 178px;
  height: 178px;
  display: block;
}

.certificate-detail {
  margin-bottom: 20px;
}
</style>
